<template>
    <table class="table">
        <tr v-for="(item,key) in data" :key="key">
            <td class="text-right" style="width:120px;">{{item.label}}</td>
            <td>
                <el-checkbox
                        v-if="item.children.length > 0"
                        :indeterminate="item.has.length > 0 && item.has.length < item.children.length"
                        :value="item.has.length > 0 && item.has.length == item.children.length"
                        @change="onCheckAllChange($event,item)">
                    全选
                </el-checkbox>
                <el-checkbox-group v-model="item.has">
                    <template v-for="child in item.children">
                        <el-checkbox :label="child.id">{{child.label}}</el-checkbox>
                    </template>
                </el-checkbox-group>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <el-button type="primary" @click="save" :loading="loading">保存</el-button>
            </td>
        </tr>
    </table>
</template>

<script>
    import {roleRule} from "@/api";

    export default {
        data() {
            return {
                key: 'children'
                , loading: true
                , data: []
            }
        }
        , props: ['pdata']
        , mounted() {
            roleRule('get', {id: this.pdata.id}, (res) => {
                this.data = res.lists;
                this.loading = false;
            }, () => {
                this.$Message.error('请求错误');
            })
        }
        , methods: {
            onCheckAllChange(checked, row) {
                if (checked) {
                    let all = [];
                    row.children.forEach(item => {
                        all.push(item.id);
                    });
                    row.has = all;
                } else {
                    row.has = []
                }
            },
            save() {
                let checked = [];
                this.data.forEach(item => {
                    item.has.forEach(val => {
                        checked.push(val)
                    })
                })
                this.loading = true;
                roleRule('post', {id: this.pdata.id, rule: checked.join(',')}, () => {
                    this.$emit('close')
                }, () => {
                    this.loading = false;
                })
            }
        }
    }
</script>
